﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ToppingControl.Models;
using WinNemoLib;
using System.Web.Security;

namespace ToppingControl.Controllers
{
    public class HeaderLineController : Controller
    {
        //
        // GET: /HeaderLine/
       public List<TopCordPlanModel.TopCordPlan_DS> Get_Header(string Noactive, string dt, string seq, string status = "", string num = "", string unStatus = "")
       {
          List<TopCordPlanModel.TopCordPlan_DS> list = new List<TopCordPlanModel.TopCordPlan_DS>();
          TopCordPlanModel mdSearch = new TopCordPlanModel();
          list = mdSearch.SEL_TOPCORDPLN(Noactive,dt , status, num, seq, unStatus);
          if (list.Count() <= 0)
          {
             return new List<TopCordPlanModel.TopCordPlan_DS>();
          }

          return list;
       }

       [AllowAnonymous]
       public ActionResult Index()
        {
           FormsAuthentication.SignOut();
           return View();
        }

       public ActionResult CheckProcess()
       {
          
          List<TopCordPlanModel.TopCordPlan_DS> list = new List<TopCordPlanModel.TopCordPlan_DS>();
          TopCordPlanModel mdSearch = new TopCordPlanModel();
          list = mdSearch.GET_NOT_FINISH();
          if (list.Count > 0)
          {          
               TopCordPlanModel.TopCordPlan_DS model = list[0];
             if (model._Actflag == "X")
             {
                if (model._Sample == "X") return RedirectToAction("New_Sample", new { seq = model._Plandt + "-" + model._Itemno });
                if (model._Tcrdcd == "") return RedirectToAction("Header_desc", new { seq = model._Plandt + "-" + model._Itemno});
                else if (model._Compcd == "") return RedirectToAction("Header_des_com", new { seq = model._Plandt + "-" + model._Itemno });
                else return RedirectToAction("Header_RuN", new { seq = model._Plandt + "-" + model._Itemno });
             }
          }
          ViewBag.shift = Session["shift"].ToString();
          return RedirectToAction("Header_line");
       }

       public void Regis_User(string shift, string emp, string code){

          FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, emp
              , DateTime.Now, DateTime.Now.AddMinutes(60), true, code);

          // Encrypt the cookie using the machine key for secure transport
          string hash = FormsAuthentication.Encrypt(ticket);
          HttpCookie cookie = new HttpCookie(
             FormsAuthentication.FormsCookieName, // Name of auth cookie
             hash); // Hashed ticket

          // Set the cookie's expiration time to the tickets expiration time
          if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

          Response.Cookies.Add
          (
              new HttpCookie
              (
                  FormsAuthentication.FormsCookieName,
                  FormsAuthentication.Encrypt(ticket)
              )
          );       

       }

       public ActionResult Register(string shift, string emp, string code)
       {
         SessionBag.Current.shift = shift;
         Session["shift"] = shift;
         Regis_User(shift,emp,code);
         return RedirectToAction("CheckProcess", new { shift = shift });        
       }

       public ActionResult Header_line(string shift)
        {                    
           List<TopCordPlanModel.TopCordPlan_DS> list = new List<TopCordPlanModel.TopCordPlan_DS>();
           ViewBag.shift = Session["shift"].ToString();
           list = Get_Header("X","","","L", " TOP 15 ");
           return View(list);
        }      

       public ActionResult Header_desc(string seq ,string shift)
        { 
           //CHECK NO UNLOCK
           ViewBag.shift = Session["shift"].ToString();
           string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

           List<TopCordPlanModel.TopCordPlan_DS> list = new List<TopCordPlanModel.TopCordPlan_DS>();

           list = Get_Header("", seqs[0].ToString(), seqs[1].ToString(),"", "TOP 1","U");

           if (list.Count() <= 0)
           {
              return View( new TopCordPlanModel.TopCordPlan_DS());
           }

            TopCordPlanModel mdSearch = new TopCordPlanModel();
           mdSearch.UPDATE(User.Identity.Name, "A", seq);
           if (StrUtil.IsEmpty(list[0]._Shift)) list[0]._Shift = shift;
           return View(list[0]);        
        }
       
       public ActionResult Header_des_com(string seq)
        {
           ViewBag.shift = Session["shift"].ToString();
           string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

           List<TopCordPlanModel.TopCordPlan_DS> list = new List<TopCordPlanModel.TopCordPlan_DS>();
           
           list = Get_Header("", seqs[0].ToString(), seqs[1].ToString(), "", "TOP 1", "U");

           if (list.Count() <= 0)
           {
              return View(new TopCordPlanModel.TopCordPlan_DS());
           }

           return View(list[0]);   
        }

       public ActionResult Header_RuN(string seq)
       {
          ViewBag.shift = Session["shift"].ToString();
          string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

          List<TopCordPlanModel.TopCordPlan_DS> list = new List<TopCordPlanModel.TopCordPlan_DS>();

          list = Get_Header("", seqs[0].ToString(), seqs[1].ToString(),"", "TOP 1", "U");

          if (list.Count() <= 0)
          {
             return View(new TopCordPlanModel.TopCordPlan_DS());
          }

          return View(list[0]);
       }

       public ActionResult New_Sample(string seq, string empnm, string sTxt, string refseq)
       {
          ViewBag.shift = Session["shift"].ToString();
         TopCordPlanModel.TopCordPlan_DS thedata;
    
             Session["empnm"] = empnm;
             Session["txt"] = sTxt;
         
         if (seq == null)
         {
            

            thedata = new TopCordPlanModel.TopCordPlan_DS();
            if (StrUtil.IsEmpty(refseq))
            {
                thedata._Plandt = WinNemoLib.DateUtil.ToDisplayDate(DateTime.Now, DateUtil.eLanguage.EN);
                thedata._Itemno = "1";
                return View(thedata);
            }
            TopCordPlanModel mdUpd = new TopCordPlanModel();
            int itemno = 0;

            if (thedata._Itemno == "" || thedata._Itemno == null)
            {
                string[] seqs = refseq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);

               thedata._Plandt = seqs[0];
               itemno = mdUpd.GET_SEQ(thedata._Plandt, seqs[1], true);           
               thedata._Itemno = itemno.ToString();              
                
               return View(thedata);
            }
         }
         else
         {
            string[] seqs = seq.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
            thedata = Get_Header("", seqs[0].ToString(), seqs[1].ToString(), "", "TOP 1", "U")[0];
         }
      

          return View(thedata);
       }



       public JsonResult Save_Sample(TopCordPlanModel.TopCordPlan_DS thedata)
       {

          using (ConnectionWrapper cnn = Nemo.GetDefaultConfiguredDbConnectionWrapper())
          {
             cnn.Open();
             cnn.BeginTransaction();
             thedata._Runflag = "X";
             thedata._Sample = "X";
             thedata._Actflag = "X";
             thedata._Topno = "1";
             thedata._smpemp = Session["empnm"].ToString();
             thedata._smpshtxt = Session["txt"].ToString();
             TopCordPlanModel mdUpd = new TopCordPlanModel();
             if (!mdUpd.Ins_Data(cnn, thedata, User.Identity.Name))
             {
                cnn.RollbackTransaction();
                return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
             }      
             cnn.CommitTransaction();

          }
          return Json(new { success = 1, message = "บันทึกเรียบร้อย" });

       }

       public ActionResult RollBack(string seq,string st="A")
        {
           ViewBag.shift = Session["shift"].ToString();
           TopCordPlanModel mdSearch = new TopCordPlanModel();
           mdSearch.ROLLBACK_STATUS(User.Identity.Name, st, seq);
           if (st == "A1") return RedirectToAction("Header_desc", new { seq = seq });

           return RedirectToAction("Header_line", "HeaderLine");         
        }

       public JsonResult ConvertDate(string sdate)
        {
            try
            {
                sdate = sdate.Replace("-", "");
                sdate = DateTime.ParseExact(sdate, "yyyyMMdd", null).ToString("yyyy-MM-dd");
                string a = DateUtil.ToDisplayDate(sdate, WinNemoLib.DateUtil.eLanguage.EN);

                if (DateUtil.IsCorrectInputDate(a))
                {
                    Conn vai = new Conn();
                    return Json(new { bln = vai.GetDateTimeDiffCurrent(sdate), message = a, sucess = 1 });
                }
                else return Json(new { bln = 0, message = "รูปแบบวันที่ไม่ถูกต้อง", sucess = 0 });
            }
            catch (Exception)
            {
                return Json(new { bln = 0, message = "รูปแบบวันที่ไม่ถูกต้อง", sucess = 0 });
                
             
            }
         

        }

       public JsonResult Save_Date(List<TopCordPlanModel.TopCordPlan_DS> theData)
        {          
           
           TopCordPlanModel.TopCordPlan_DS data = theData[0];
           
           TopCordPlanModel mdUpd= new TopCordPlanModel();
           data._Empname = User.Identity.Name;
           if (mdUpd.UPDATE_ALL(data))
           {
              return Json(new { success = 1, message = "บันทึกเรียบร้อย" });
           }
           else
           {
              return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
           }

        }

       public JsonResult Upd_Status(string seq,string status)
       {          

          TopCordPlanModel mdUpd = new TopCordPlanModel();
          
          if (mdUpd.UPDATE(User.Identity.Name,status,seq))
          {
             return Json(new { success = 1, message = "" });
          }
          else
          {
             return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
          }

       }    

       /********RUN AND FINISH AND SKIP ********/

       public JsonResult Get_Author(string users, string pass)
       {

          System.Data.DataTable dt = LoginAuthorize.DataAcess.MasterGroupNameDA.SEL_UserInfo(users, LoginAuthorize.EnCodeMD5.MD5CalcString(pass), "13-001");
          if (dt == null)
          {
             return Json(new { success = 0, message = "The user name or password provided is incorrect." });         
          }
          return Json(new { success = 1, message = "" });
       }


       public JsonResult SKIP_ITEM(string seq, string empnm, string sTxt)
       {  
           
           TopCordPlanModel mdSearch = new TopCordPlanModel();

           if (mdSearch.SKIP_STATUS(seq, empnm, sTxt)==true)
           {
               return Json(new { success = 1, message = "" });
           }
           else
           {
               return Json(new { success = 0, message = "ไม่สามารถบันทึกได้" });
           }
       }

    }


}
